"""
债券条款分析智能体

基于LangGraph ReAct模式，分析债券的基本信息和特殊条款。
"""

from typing import Dict, Any, List, Optional
from langchain_core.tools import Tool

from agents import BondAnalysisAgent, LLMConfig
from tools.bond_data_provider import bond_data_provider


class BondTermsAnalysisAgent(BondAnalysisAgent):
    """债券条款分析智能体"""
    
    def __init__(self, llm_config: Optional[LLMConfig] = None):
        super().__init__(
            name="bond_terms_analysis",
            description="分析债券的基本信息和特殊条款",
            llm_config=llm_config
        )
        
        self.analysis_dimensions = ["terms", "clauses"]
    
    def get_tools(self) -> List[Tool]:
        """获取债券条款分析所需的工具"""
        
        async def get_bond_basic_terms(bond_code: str) -> str:
            """获取债券基本条款信息（使用修复后的多数据源）"""
            try:
                info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not info:
                    return f"未找到债券{bond_code}的信息"
                
                result = "=== 债券基本条款 ===\n"
                result += f"债券代码: {info.get('债券代码')}\n"
                result += f"债券简称: {info.get('债券简称')}\n"
                result += f"发行人: {info.get('正股名称', 'N/A')}\n"
                result += f"正股代码: {info.get('正股代码', 'N/A')}\n"
                result += f"发行规模: {info.get('发行规模', 'N/A')}亿元\n"
                result += f"剩余规模: {info.get('剩余规模', 'N/A')}亿元\n"
                result += f"债券评级: {info.get('信用评级', 'N/A')}\n"
                result += f"上市时间: {info.get('上市时间', 'N/A')}\n"
                result += f"到期日: {info.get('到期日', 'N/A')}\n"
                result += f"转股价: {info.get('转股价', 'N/A')}元\n"
                result += f"转股起始日: {info.get('转股起始日', 'N/A')}\n"
                
                return result
            except Exception as e:
                return f"获取债券基本条款失败: {str(e)}"
        
        async def analyze_special_clauses(bond_code: str) -> str:
            """分析债券特殊条款（使用修复后的多数据源）"""
            try:
                info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not info:
                    return "未找到债券特殊条款信息"
                
                result = "=== 特殊条款分析 ===\n\n"
                
                # 回售条款
                recall_price = info.get('回售触发价', 0)
                result += f"【回售条款】\n"
                result += f"回售触发价: {recall_price}元\n"
                if recall_price and recall_price > 0:
                    bond_price = info.get('债现价', 0)
                    if bond_price > 0:
                        distance = ((recall_price / bond_price) - 1) * 100
                        result += f"当前债券价格: {bond_price}元\n"
                        result += f"距离触发: {distance:.2f}%\n"
                        if abs(distance) < 10:
                            result += "⚠️ 接近回售触发价，持有人可能行使回售权\n"
                else:
                    result += "暂无回售条款或未披露\n"
                
                result += "\n"
                
                # 强赎条款
                redemption_price = info.get('强赎触发价', 0)
                result += f"【强制赎回条款】\n"
                result += f"强赎触发价: {redemption_price}元\n"
                result += f"强赎触发比: {info.get('强赎触发比', 'N/A')}%\n"
                result += f"强赎状态: {info.get('强赎状态', 'N/A')}\n"
                
                if redemption_price and redemption_price > 0:
                    stock_price = info.get('正股价', 0)
                    if stock_price > 0:
                        distance = ((redemption_price / stock_price) - 1) * 100
                        result += f"当前正股价格: {stock_price}元\n"
                        result += f"距离触发: {distance:.2f}%\n"
                        if distance < 0:
                            result += "⚠️ 已达到强赎触发价，发行人可能强制赎回\n"
                        elif distance < 10:
                            result += "⚠️ 接近强赎触发价，注意强赎风险\n"
                
                # 强赎条款详细说明
                clause_detail = info.get('强赎条款', '')
                if clause_detail:
                    result += f"\n强赎条款详情:\n{clause_detail}\n"
                
                result += "\n"
                
                # 转股价值分析
                conversion_value = info.get('转股价值', 0)
                conversion_premium = info.get('转股溢价率', 0)
                result += f"【转股价值】\n"
                result += f"转股价值: {conversion_value}元\n"
                result += f"转股溢价率: {conversion_premium}%\n"
                
                if conversion_value and conversion_value > 0:
                    if conversion_premium < 0:
                        result += "✓ 转股溢价率为负，转股有利\n"
                    elif conversion_premium < 10:
                        result += "✓ 转股溢价率较低，转股价值较高\n"
                    elif conversion_premium < 30:
                        result += "转股溢价率适中\n"
                    else:
                        result += "⚠️ 转股溢价率较高，持有债券更有利\n"
                
                return result
            except Exception as e:
                import traceback
                return f"分析特殊条款失败: {str(e)}\n{traceback.format_exc()}"
        
        async def analyze_payment_terms(bond_code: str) -> str:
            """分析债券付息方式（使用修复后的多数据源）"""
            try:
                info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not info:
                    return "未找到债券付息信息"
                
                result = "=== 付息方式分析 ===\n\n"
                
                # 纯债价值
                pure_bond_value = info.get('纯债价值', 0)
                result += f"【纯债价值】\n"
                result += f"纯债价值: {pure_bond_value}元\n"
                
                pure_bond_premium = info.get('纯债溢价率', 0)
                if pure_bond_premium:
                    result += f"纯债溢价率: {pure_bond_premium}%\n"
                    
                    if pure_bond_premium < 10:
                        result += "✓ 纯债溢价率较低，债券保护性好\n"
                    elif pure_bond_premium < 30:
                        result += "纯债溢价率适中\n"
                    else:
                        result += "⚠️ 纯债溢价率较高，债券保护性较弱\n"
                elif pure_bond_value > 0:
                    bond_price = info.get('债现价', 100)
                    if bond_price > 0:
                        calc_premium = ((bond_price / pure_bond_value) - 1) * 100
                        result += f"纯债溢价率(计算): {calc_premium:.2f}%\n"
                        
                        if calc_premium < 10:
                            result += "✓ 纯债溢价率较低，债券保护性好\n"
                        elif calc_premium < 30:
                            result += "纯债溢价率适中\n"
                        else:
                            result += "⚠️ 纯债溢价率较高，债券保护性较弱\n"
                
                result += "\n"
                
                # 到期赎回信息
                result += f"【到期赎回】\n"
                result += f"到期赎回价: {info.get('到期赎回价', 'N/A')}元\n"
                result += f"到期日: {info.get('到期日', 'N/A')}\n"
                
                return result
            except Exception as e:
                return f"分析付息方式失败: {str(e)}"
        
        async def analyze_scale_and_rating(bond_code: str) -> str:
            """分析发行规模和评级（使用修复后的多数据源）"""
            try:
                info = await bond_data_provider.get_bond_basic_info(bond_code)
                if not info:
                    return "未找到债券规模和评级信息"
                
                result = "=== 发行规模与评级分析 ===\n\n"
                
                # 发行规模
                issue_scale = info.get('发行规模', 0)
                remaining_scale = info.get('剩余规模', 0)
                result += f"【发行规模】\n"
                result += f"发行规模: {issue_scale}亿元\n"
                result += f"剩余规模: {remaining_scale}亿元\n"
                
                if issue_scale and issue_scale > 0 and remaining_scale and remaining_scale > 0:
                    redemption_ratio = (1 - remaining_scale / issue_scale) * 100
                    result += f"已赎回比例: {redemption_ratio:.2f}%\n"
                    
                    if redemption_ratio > 50:
                        result += "✓ 大部分已赎回，流动性可能降低\n"
                    elif redemption_ratio > 20:
                        result += "部分已赎回\n"
                    else:
                        result += "赎回比例较低\n"
                
                result += "\n"
                
                # 债券评级
                rating = info.get('信用评级', 'N/A')
                result += f"【信用评级】\n"
                result += f"债券评级: {rating}\n"
                
                # 评级分析
                if rating in ['AAA', 'AA+']:
                    result += "✓ 信用评级优秀，违约风险极低\n"
                    result += "适合风险偏好较低的投资者\n"
                elif rating in ['AA', 'AA-']:
                    result += "信用评级良好，违约风险较低\n"
                    result += "适合稳健型投资者\n"
                elif rating in ['A+', 'A']:
                    result += "信用评级一般，需关注信用风险\n"
                    result += "适合能承受一定风险的投资者\n"
                else:
                    result += "⚠️ 评级信息不足或评级较低\n"
                    result += "建议谨慎投资，密切关注发行人信用状况\n"
                
                return result
            except Exception as e:
                return f"分析发行规模和评级失败: {str(e)}"
        
        # 创建工具列表
        tools = [
            Tool(
                name="get_bond_basic_terms",
                description="获取债券的基本条款信息，包括发行人、发行规模、评级、到期时间等",
                func=lambda bond_code: None,
                coroutine=get_bond_basic_terms,
            ),
            Tool(
                name="analyze_special_clauses",
                description="分析债券的特殊条款，包括回售条款、强制赎回条款、转股条款等",
                func=lambda bond_code: None,
                coroutine=analyze_special_clauses,
            ),
            Tool(
                name="analyze_payment_terms",
                description="分析债券的付息方式，包括票面利率、纯债价值、到期收益率等",
                func=lambda bond_code: None,
                coroutine=analyze_payment_terms,
            ),
            Tool(
                name="analyze_scale_and_rating",
                description="分析债券的发行规模和信用评级",
                func=lambda bond_code: None,
                coroutine=analyze_scale_and_rating,
            ),
        ]
        
        return tools
    
    def get_system_prompt(self) -> str:
        """获取系统提示词"""
        return """你是一个专业的债券条款分析专家，负责分析可转债的各项条款和风险点。

你的分析流程：
1. 首先使用 get_bond_basic_terms 工具获取债券基本条款信息
2. 使用 analyze_special_clauses 分析特殊条款（回售、强赎等）
3. 使用 analyze_payment_terms 分析付息方式和收益率
4. 使用 analyze_scale_and_rating 分析发行规模和评级
5. 基于获取的信息，进行综合条款风险分析

分析要点：
- 回售条款保护持有人利益，关注触发条件
- 强赎条款保护发行人利益，关注触发条件
- 转股条款影响转股价值，关注转股溢价率
- 付息方式影响投资收益，关注到期收益率和纯债价值
- 发行规模影响流动性
- 债券评级反映信用风险

请逐步使用工具获取信息，展示你的分析推理过程，最后给出：
1. 条款特点总结
2. 主要风险点
3. 投资建议
"""


# 全局实例
bond_terms_agent = BondTermsAnalysisAgent()